import logging

from pylons import request, response, session, tmpl_context as c
from pylons.decorators.secure import authenticate_form
from pylons.controllers.util import abort, redirect_to, url_for

from pglite.lib.base import BaseController, render
from pglite.lib.usermanager import UserManager

log = logging.getLogger(__name__)

class SecurityController(BaseController):

    def __before__(self):
        self.userManager = UserManager()

    def register(self):
        if session.get("register_error"):
            c.register_error = session.get("register_error")
            session["register_error"] = None
            session.save()
    
        return render('/security/register.mako')
    
    @authenticate_form
    def do_register(self):
    
        # Retrieve parameters
        login = request.params.get("login")
        email = request.params.get("email")
        password = request.params.get("password")
        
        if self.userManager.validateLogin(login) == False:
            session["register_error"] = "Login is already used"
            session.save()
            redirect_to('/register')
            
        if self.userManager.validatePassword(password) == False:
            session["register_error"] = "Password does not match the required criterias"
            session.save()
            redirect_to('/register')
        
        # Create user
        theUser = self.userManager.createUser(login, password, email)
        
        return theUser.validation_key
    
    def user(self, id=None):
        pass
    
    def edit(self, id=None):
        pass
    
    def validate(self, id=None, key=None):
        if id is not None:
            theUser = self.userManager.getUserById(id)
            if theUser.validation_key == key:
                theUser.type = "R"
                self.userManager.insertUser(theUser)
        else:
            redirect_to('/')
        
    def do_edit(self):
        pass
    
    def do_login(self):
        pass
    
    def do_logout(self):
        pass
